#!/bin/bash
# vim:fdm=marker fmr=[[[,]]] cms=\ #%s

[[ -z $SOAR ]] && SOAR=/opt/soar
PATH=$PATH:$SOAR/common/bash/soar
. soar.sh

build()
{ #[[[
    local svr_def=$1
    local svr=$2

    rm -f _svc_map.c
    local skeleton=$SVCENV_DIR/sys/skeleton
    local args=$(awk '
BEGIN {
    FS="=";
    svc_map_c="_svc_map.c";
}
/ *SRCS *=/ { src_num=split($2, a_src, " "); }
/ *SVCS *=/ { svc_num=split($2, a_svc, " "); }
/ *OBJS *=/ { obj_num=split($2, a_obj, " "); }
/ *LIBS *=/ { lib_num=split($2, a_lib, " "); }
END {
    printf(" -o '$SVCENV_DIR'/bin/svr_'$svr'");
    printf(" -f %s", svc_map_c);
    for(i=1; i<=src_num; i++)
    {
        printf(" -f %s", a_src[i]);
    }
    for(i=1; i<=obj_num; i++)
    {
        printf(" -l %s", a_obj[i]);
    }
    for(i=1; i<=lib_num; i++)
    {
        printf(" -l %s", a_lib[i]);
    }
    printf(" -f '$SVCENV_DIR'/sys/skeleton/svr_skeleton.c");

    printf("#include <svr_skeleton.h>\n\n") >> svc_map_c;
    printf("char *SERVER_NAME=\"'$svr'\";\n\n") >> svc_map_c;
    printf("static char request[MSG_SIZE];\n") >> svc_map_c;
    printf("static char respond[MSG_SIZE];\n") >> svc_map_c;
    printf("\n") >> svc_map_c;
    for(i=1; i<=svc_num; i++)
    {
        printf("DEFINE_SERVICE(%s)\n", a_svc[i], a_svc[i]) >> svc_map_c;
        printf(" -s %s_%s:SVC_%s", group, a_svc[i], a_svc[i]);
    }
}
' $svr_def)
    if [[ -r $SVCENV_DIR/lib/libcm.a ]]
    then
        args="$args -l -lcm"
    fi
    if [[ -r $SVCENV_DIR/lib/libdbauto.a ]]
    then
        args="$args -l -ldbauto"
    fi
    args="$args -l -lsoar_g -l -lcrypto -l -lm"
    #echo $args
    export CFLAGS="$CFLAGS -g -Wall -I. -I$SVCENV_DIR/sys/skeleton -I$SVCENV_DIR/src/include -I$SOAR/common/c/include -I$ORACLE_HOME/precomp/public -L$SVCENV_DIR/lib -L$SOAR/common/c/lib"
    #echo $CFLAGS

    buildserver -v $args -r Oracle_XA
    if (( $? != 0 ))
    then
        echo "Error: build $svr fail"
        return 1
    fi
} #]]]

main()
{ #[[[
    if [[ -z $SVCENV_DIR ]]
    then
        echo "Error: SVCENV_DIR not set"
        return 1
    fi
    if [[ -z $SVCENV_CNFG ]]
    then
        echo "Error: SVCENV_CNFG not set"
        return 1
    fi

    local svr_def=svr.def
    if [[ ! -r $svr_def ]]
    then
        echo "Error: $svr_def not readable"
        return 1
    fi

    local svr=$(basename $PWD | tr 'a-z' 'A-Z')
    local svr_cnfg=$(cnfg_get_property $SVCENV_CNFG SERVER svr_${svr})
    if [[ -z $svr_cnfg ]]
    then
        echo "Error: Server($svr) not set in $conf"
        return 1
    fi

    build $svr_def $svr
    if (( $? != 0 ))
    then
        return 1
    fi
} #]]]

LANG=C
main $@
exit $?
